package com.msb.dongbao.portal.web.filter;

import com.alibaba.fastjson.JSONObject;
import com.msb.dongbao.common.util.BodyReaderHttpServletRequestWrapper;
import com.msb.dongbao.common.util.CheckUtils;
import com.msb.dongbao.portal.web.util.HttpParamUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author: mayu
 * @date: 2021年05月31日 11:25
 * 签名校验过滤器
 */
@Component
@Slf4j
public class SignAuthFilter implements Filter {
    //放行的请求
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("/ums-member/login", "/ums-member/edit")));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("SignAuthFilter过滤器生效...");
        //HttpServletRequest req = (HttpServletRequest) request;
        HttpServletRequest req = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
        HttpServletResponse resp = (HttpServletResponse) response;

        String path = req.getRequestURI().substring(req.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);

        if (allowedPath) {//不走过滤
            chain.doFilter(req, resp);
        } else {//走过滤
            //获取参数,统一参数，不管是url还是body
            SortedMap allParams = HttpParamUtils.getAllParams(req);
            log.info("请求中的所有参数：" + allParams);
            //校验签名
            boolean b = CheckUtils.checkSign(allParams);
            log.info("签名校验结果：" + b);
            if (b) {
                chain.doFilter(req, resp);
            } else {
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter printWriter = resp.getWriter();

                JSONObject param = new JSONObject();
                param.put("code", "-1");
                param.put("msg", "签名错了");
                printWriter.append(param.toJSONString());
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
